package com.kcs.fxmargin.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.json.JSONObject;
import org.json.JSONArray;

import com.kcs.common.utils.Constant;
import com.kcs.common.utils.commonUtils;
import com.kcs.fxmargin.action.form.LoginActionForm;
import com.kcs.fxmargin.bo.CustomerInformationBO;
import com.kcs.fxmargin.model.MCustInfo;
import com.kcs.fxmargin.model.TAccOnline;
import com.kcs.fxmargin.service.CommonService;
import com.kcs.fxmargin.service.AccOnlineService;
import com.kcs.fxmargin.service.CustInfoService;

/**
 * Servlet implementation class DepositWithdrawServlet
 */
public class DepositWithdrawServlet extends HttpServlet {
	private Logger log = Logger.getLogger(Constant.LOG_FX);
	
	private static final long serialVersionUID 	= 1L;
	private static final String CONTENT_TYPE 	= "text/html; charset=utf-8";	

	private AccOnlineService service 			= new AccOnlineService();
	private CustInfoService	 custService		= new CustInfoService();
    private CommonService common 				= new CommonService();
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public DepositWithdrawServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.setCharacterEncoding("UTF-8");
        PrintWriter out = response.getWriter();
        response.setContentType(CONTENT_TYPE);
        
        System.out.println("DepositWithdrawServlet : Start");
        LoginActionForm loginBean = null;
        try {
        	
        	HttpSession session = request.getSession();
        	
        	if(session == null) {
        		JSONObject json = new JSONObject();
                json.put("data", "to");
                json.write(out);
        	} else {
        		loginBean = (LoginActionForm) request.getSession().getAttribute(Constant.LOGIN_DATA_SESSION);
    			
            	String id					= request.getParameter("id");
            	String custInfoId			= request.getParameter("custInfoId");
            	String cifNo 				= request.getParameter("cifNo");
            	String customerName 		= request.getParameter("customerName");
            	String marginAccNo	  		= request.getParameter("marginAccNo");
            	String marginAccName 		= request.getParameter("marginAccName");
            	String transactionDate 		= request.getParameter("transactionDate");
            	String valueDate			= request.getParameter("valueDate");
            	String depositWithdraw	  	= request.getParameter("depositWithdraw");
            	String amount 				= request.getParameter("amount");
            	String referanceNo 			= request.getParameter("referanceNo");
            	String action	  			= request.getParameter("action");
            	String userId				= "";
            	int rowVers					= Integer.parseInt(request.getParameter("rowVersion"));
            	String result				= "";
            	
            	if(loginBean != null) {
            		userId = loginBean.getUserId();
            	}
            	
            	System.out.println("id		 			= " + id);
            	System.out.println("custInfoId  		= " + custInfoId);	
            	System.out.println("cifNo 				= " + cifNo);
            	System.out.println("customerName 		= " + customerName);
            	System.out.println("marginAccNo 	 	= " + marginAccNo);
            	System.out.println("marginAccName 		= " + marginAccName);
            	System.out.println("transactionDate 	= " + transactionDate);
            	System.out.println("valueDate 			= " + valueDate);	
            	System.out.println("depositWithdraw 	= " + depositWithdraw);
            	System.out.println("amount 				= " + amount);
            	System.out.println("referanceNo 		= " + referanceNo);
            	System.out.println("updateBy 	 		= " + userId);
            	System.out.println("rowVersion 			= " + rowVers);		
            	System.out.println("action 	 			= " + action);
            	
            	TAccOnline accOnline = new TAccOnline();
            	
            	accOnline.setId(id);
            	accOnline.setCustInfoId(custInfoId);
            	accOnline.setType(depositWithdraw);
            	accOnline.setAmount(convertStringtoBigDecimal(amount));
            	accOnline.setRefNo(referanceNo);
            	accOnline.setAsOfDate(commonUtils.convertStrtoDate_HHMMSS(transactionDate, "dd/MM/yyyy"));
            	accOnline.setValueDate(commonUtils.convertStrtoDate_HHMMSS(valueDate, "dd/MM/yyyy"));
            	accOnline.setActiveStatus("A");
            	accOnline.setRowVersion(rowVers);
            	accOnline.setCreateby(userId);
            	accOnline.setUpdateBy(userId);
            	
            	if("insert".equals(action)) result = service.insert(accOnline);
            	else if ("update".equals(action)){
            		
            		int rowVersion = common.getRowVersion(Constant.ACC_ONLINE, accOnline.getId());
            		
            		if(rowVersion <= accOnline.getRowVersion()){
            			accOnline.setRowVersion(rowVersion + 1);
            			result = service.update(accOnline);
            		}else{
            			log.error("Concurrent Data Access." + Constant.ACC_ONLINE + " [id = " + accOnline.getId() + "]");
            			result = "Dup";
            		}
            		
            	}
            	
            	if("searchCustomer".equals(action)){
            		
            		MCustInfo custInfo = new MCustInfo();
            		custInfo.setCifNo(cifNo);
            		custInfo.setCustName(customerName);
            		
            		JSONObject json = new JSONObject();
                    json.put("data", searchCustomer(custInfo));
                    json.write(out);
            	}else{
            		JSONObject json = new JSONObject();
                    json.put("data", result);
                    json.write(out);
            	}
            	
        	}     	
        	
        } catch (Exception e) {
        	log.error(e);
            out.print("{\"status\": \"failed\", \"message\": \"" +
                      e.getMessage() + "\"}");
        } finally {
            out.close();
        }

        System.out.println("DepositWithdrawServlet : End");
	}
	
	private BigDecimal convertStringtoBigDecimal(String number) throws Exception {
		BigDecimal bigDecimal = new BigDecimal(0);
		
		if(number != null && !"".equals(number)) bigDecimal = new BigDecimal(number);
		
		return bigDecimal;
	}
	
	private JSONArray searchCustomer(MCustInfo custInfo) throws Exception {
		
		List<CustomerInformationBO> custList = custService.searchPopupCustomer(custInfo);
		JSONArray jsonArray = new JSONArray();
		 
		for(CustomerInformationBO bo : custList){
			jsonArray.put(bo.getJSONObject());
		}

		return jsonArray;
	}

}
